//
//  ShoppingViewController.m
//  NineGroupProject
//
//  Created by dllo on 15/12/22.
//  Copyright © 2015年 蓝鸥科技. All rights reserved.
//

#import "ShoppingViewController.h"
#import "AFNetworking.h"
#import "LSAppTools.h"
#import "ShoppingCollectionViewCell.h"
#import "HeardShoppingCollectionViewCell.h"
#import "LikeImageCollectionViewCell.h"
#import "LikeShoppingCollectionViewCell.h"
#import "DataHeadShoppingCell.h"
#import "DataShoppingCell.h"
#import "ShoppingDataCollectionViewCell.h"
#import "RootCollectionReusableView.h"
#import "MJRefresh.h"
#import "DataShoppingViewController.h"
#import "DataViewController.h"
#import "ShoppingDataViewController.h"
@interface ShoppingViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, LikeShoppingCollectionViewCellDelegate>

@end

@implementation ShoppingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UILabel *customLab = [[UILabel alloc] initWithFrame:CGRectZero];
    [customLab setTextColor:[UIColor whiteColor]];
    [customLab setText:@"购物"];
    customLab.textAlignment = NSTextAlignmentCenter;
    customLab.font = [UIFont boldSystemFontOfSize:20];
    [customLab sizeToFit];
    self.navigationItem.titleView = customLab;
    [self showCollectionView];
    
    
}
#pragma mark - collectionView初始化

-(void)showCollectionView{
    self.bigArray = [NSMutableArray array];
    self.allArray = [NSMutableArray array];
    self.littleArray = [NSMutableArray array];
    
    [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"like"];
    
    self.userD = [[NSUserDefaults standardUserDefaults] objectForKey:@"like"];
    
    self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
    
    // 设置滚动方向
    self.flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 100 * HEI) collectionViewLayout:self.flowLayout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectionView];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    // 注册cell
    [self.collectionView registerClass:[ShoppingCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    
    [self.collectionView registerClass:[LikeShoppingCollectionViewCell class] forCellWithReuseIdentifier:@"likeCell"];
    
    [self.collectionView registerClass:[HeardShoppingCollectionViewCell class] forCellWithReuseIdentifier:@"headCell"];
    
    
    
    // 注册表尾
    [self.collectionView registerClass:[RootCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"foot"];
    
    
    [LSAppTools getWithUrlString:@"http://api.xiangqu.com/category/out/children" body:nil block:^(id result) {
        
        NSMutableDictionary *dic = result;
        NSMutableArray *array = [dic objectForKey:@"data"];
        for (NSMutableDictionary *dic in array) {
            HeadShoppingModel *model = [[HeadShoppingModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.bigArray addObject:model];
        }
        [self.collectionView reloadData];
    }];
    self.isUpLoading = NO;
    [self addHeader];
    [self addFooter];
    
    // 注册通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeCell) name:@"changeCell" object:nil];
    
}

#pragma mark - 表头的初始化方法
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    RootCollectionReusableView *footView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"foot" forIndexPath:indexPath];
    
    return footView;
}


#pragma mark --上拉加载更多
- (void)addFooter
{
        __unsafe_unretained ShoppingViewController *vc = self;

    self.collectionView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
                // 进入刷新状态就会回调这个Block
        
                vc.nextPage ++;
                vc.isUpLoading = YES;//标记为上拉操作
                [vc GetPersonList:vc.nextPage];//请求数据
        
    }];

}
#pragma mark --下拉刷新
- (void)addHeader{
    __block ShoppingViewController *vc = self;//因为block块里用self会报警告,所以需要将self声明成block变量

    self.collectionView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if ([self.userD isEqualToString:@"0"]){
            vc.nextPage = 0;
        }
        else
        {
            vc.nextPage = 1;
        }//记录页码的
        vc.isUpLoading = NO;//标记为下拉操作
        [vc GetPersonList:vc.nextPage];//重新请求数据
        
    }];
    [self.collectionView.header beginRefreshing];
}

-(void)GetPersonList:(NSInteger)nextCursor{
        if ([self.userD isEqualToString:@"0"]) {
        
        NSString *str = [NSString stringWithFormat:@"%ld", self.nextPage];
        NSDictionary *bodyDic = @{@"key":@"92536fa768bbfa8b7988d18f31a6cd9", @"page":str,  @"t":@"1448596381685", @"tagid":@"0", @"version":@"2.0.08"};
        
        [LSAppTools getWithUrlString:@"http://api.xiangqu.com/search/list" body:bodyDic block:^(id result) {
            NSMutableDictionary *dic = result;
            NSMutableDictionary *dataDic = [dic objectForKey:@"data"];
            NSMutableArray *array = [dataDic objectForKey:@"records"];
            if (self.isUpLoading == NO) {
                [self.allArray removeAllObjects];
            }
            for (NSMutableDictionary *dic in array) {
                ShoppingModel *model = [[ShoppingModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.allArray addObject:model];
            }
            [self.collectionView.header endRefreshing];
            [self.collectionView.footer endRefreshing];
            [self.collectionView reloadData];
        }];
    }
    else{
        NSString *str = [NSString stringWithFormat:@"%ld", self.nextPage];
        NSDictionary *bodyDic = @{@"key":@"cce9da70d5dd806461082142ba7412bf", @"p":str,  @"t":@"1448629232914",  @"version":@"2.0.08"};
        [LSAppTools getWithUrlString:@"http://api.xiangqu.com/android/allfaver" body:bodyDic block:^(id result) {
            NSMutableDictionary *dic = result;
            NSMutableArray *dataArray = [dic objectForKey:@"data"];
            NSMutableDictionary *listDic = [dataArray objectAtIndex:0];
            NSMutableArray *listArray = [listDic objectForKey:@"list"];
            if (self.isUpLoading == NO) {
                [self.littleArray removeAllObjects];
            }
            for (NSMutableDictionary *dic in listArray) {
                LikeModel *model = [[LikeModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.littleArray addObject:model];
            }
            [self.collectionView.header endRefreshing];
            [self.collectionView.footer endRefreshing];
            [self.collectionView reloadData];
        }];
    }
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
        return 2;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        self.flowLayout.itemSize = CGSizeMake(70 * WID, 80 * HEI);
        self.flowLayout.minimumLineSpacing = 10 * HEI;
        // 设置最小列间距
        self.flowLayout.minimumInteritemSpacing = 15 * WID;
        // 设置item与四周边界的距离  上左下右
        self.flowLayout.sectionInset = UIEdgeInsetsMake(10 * HEI, 20                                                            * WID, 10 * HEI, 20 * WID);
        //设置section = 0表尾的大小
        self.flowLayout.footerReferenceSize = CGSizeMake(0, 60 * HEI);
        
    }
    else if(indexPath.section == 1){
        
        if ([self.userD isEqualToString:@"0"]) {
            
            self.flowLayout.itemSize = CGSizeMake(170 * WID, 230 * HEI);
            self.flowLayout.minimumLineSpacing = 8 * HEI;
            // 设置最小列间距
            self.flowLayout.minimumInteritemSpacing = 10 * WID;
            // 设置item与四周边界的距离  上左下右
            self.flowLayout.sectionInset = UIEdgeInsetsMake(10 * HEI, 10 * WID, 10 * HEI, 10 * WID);
        }
        
        else if ([self.userD isEqualToString:@"1"]){
            
            
            self.flowLayout.itemSize = CGSizeMake(WIDTH, 300 * HEI);
            // 设置item与四周边界的距离  上左下右
            self.flowLayout.sectionInset = UIEdgeInsetsMake(0, 10 * WID, 0, 10 * WID);
            
            }
        
        self.flowLayout.footerReferenceSize = CGSizeMake(0, 0);
        
    }
    
    return self.flowLayout.itemSize;
    
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    if (section == 0) {
        
        return self.bigArray.count;
    }
    else{
        if ([self.userD isEqualToString:@"0"]) {
            
            return self.allArray.count;
        }
        else{
            
            return self.littleArray.count;
        }
        
        
    }
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        static NSString *heaadStr = @"headCell";
        HeardShoppingCollectionViewCell  *headCell = [collectionView dequeueReusableCellWithReuseIdentifier:heaadStr forIndexPath:indexPath];
        HeadShoppingModel *model = [self.bigArray objectAtIndex:indexPath.item];
        headCell.model = model;
        return headCell;
        
    }
    else{
        
        if ([self.userD isEqualToString:@"0"]) {
            static NSString *str = @"cell";
            ShoppingCollectionViewCell  *cell = [collectionView dequeueReusableCellWithReuseIdentifier:str forIndexPath:indexPath];
            
            ShoppingModel  *model = [self.allArray objectAtIndex:indexPath.item];
            cell.model =model;
            
            return cell;
        }
        else{
            
            static NSString *str = @"likeCell";
            LikeShoppingCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:str forIndexPath:indexPath];
            cell.likeShoppingCollectionViewDelegate = self;
            
            LikeModel *model = [self.littleArray objectAtIndex:indexPath.item];
            cell.model = model;
            cell.index = indexPath;
            return cell;
            
        }
    }
    
}


-(void)byDetailViewController: (NSString *)productId{
    
    DataViewController *dataVC = [[DataViewController alloc] init];
    dataVC.productId = productId;
    [self presentViewController:dataVC animated:YES completion:^{
    }];
}

// 接收通知的方法改变不同的cell
-(void)changeCell{
    
    self.userD = [[NSUserDefaults standardUserDefaults]objectForKey:@"like"];
    [self addHeader];
    [self addFooter];
    
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        DataShoppingViewController *dataSVC = [[DataShoppingViewController alloc] init];
        // 跳到下一级页面tabBar隐藏
        dataSVC.hidesBottomBarWhenPushed = YES;
        HeadShoppingModel *model = [self.bigArray objectAtIndex:indexPath.item];
        dataSVC.dataId = model.dataId;
        dataSVC.tittleName = model.name;
        [self.navigationController pushViewController:dataSVC animated:YES];        
        
    }
    else if (indexPath.section == 1) {
        
        if ([self.userD isEqualToString:@"0"]) {
            
            DataViewController *dataVC = [[DataViewController alloc] init];
            
            
            ShoppingModel *model = [self.allArray objectAtIndex:indexPath.row];
            
            dataVC.hidesBottomBarWhenPushed = YES;
            dataVC.productId = model.productId;
            [self presentViewController:dataVC animated:YES completion:^{
                
            }];
        }
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
